//
//  STFollowLisTableViewCell.swift
//  Story
//
//  Created by 汤泽川 on 2019/5/10.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import PKHUD
import Kingfisher

class STFollowLisTableViewCell: UITableViewCell {
    let avatarImageView = UIImageView()
    let userNameLabel = UILabel()
    let followBtn = UIButton()
    var userInfo : STUserInfo?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        avatarImageView.layer.cornerRadius = 18
        avatarImageView.layer.masksToBounds = true
        self.contentView.addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview().inset(12)
            make.left.equalToSuperview().offset(12)
            make.size.equalTo(CGSize(width: 36, height: 36))
        }
        userNameLabel.textColor = .gray
        userNameLabel.font = .systemFont(ofSize: 14)
        self.contentView.addSubview(userNameLabel)
        userNameLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(avatarImageView.snp_right).offset(5)
            make.height.equalToSuperview()
        }
        
        followBtn.setTitle("关注", for: .normal)
        followBtn.setTitle("已关注", for: .selected)
        followBtn.backgroundColor = .red
        followBtn.layer.cornerRadius = 4
        self.contentView.addSubview(followBtn)
        followBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-18)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 80, height: 30))
        }
        followBtn.isSelected = true
        _ = followBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.followBtn.isSelected = !self.followBtn.isSelected
            STUserService.shareInstance.changeFollowStatus(targetId: self.userInfo!.id, status: self.followBtn.isSelected ? 1 : 0).result(callBack: { (error) in
                if error != nil {
                    HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                    self.followBtn.isSelected = !self.followBtn.isSelected
                }
            })
        })
    }
    
    func configureCell(userInfo : STUserInfo) {
        self.userInfo = userInfo
        avatarImageView.kf.setImage(with:URL(string: userInfo.avatarUrl ?? ""), placeholder: #imageLiteral(resourceName: "user_default"))
        userNameLabel.text = userInfo.username
        followBtn.isSelected = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
